package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceIpml implements ReportService {





    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    WorkSpaceService workSpaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
//    public TurnoverReportVO getStatistics(String begin, String end) {
//        List<Orders> list = reportMapper.getByTime(begin,end);
//        String date = "";
//        String turnover = "";
//        for(Orders orders : list){
//            if(orders.equals(list.get(list.size() - 1))){
//                String time = orders.getOrderTime().format(DateTimeFormatter.ISO_DATE);
//                date = date + time;
//                turnover = turnover + orders.getAmount();
//            }else {
//                String time = orders.getOrderTime().format(DateTimeFormatter.ISO_DATE);
//                date = date + time + ",";
//                turnover = turnover + orders.getAmount() + ",";
//            }
//        }
//
//        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
//                .turnoverList(turnover)
//                .dateList(date)
//                .build();
//        return turnoverReportVO;
//    }


    //视频方法
    public TurnoverReportVO getStatistics(LocalDate begin, LocalDate end) {
        //处理时间
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //处理营业额
        List<Double> turnoverList = new ArrayList<>();
        for(LocalDate date : dateList){
            //将一天的时间按照时分秒处理:一天的开始---零点
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //一天的末尾---23:59
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);

            //将查询所需要的数据封装起来
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);

            Double turnover = ordersMapper.findByTime(map);
            //考虑营业额为空的清空
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);

        }

        //将时间和营业额集合转为字符串类型并加入返回数据中
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();

        return turnoverReportVO;
    }


    /**
     * 视频方法用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //封装日期集合
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //封装用户集合
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);

            //先查询总用户
            Map map = new HashMap<>();
            map.put("end",endTime);
            Integer totalUser = userMapper.findByMap(map);
            map.put("begin",beginTime);
            Integer newUser = userMapper.findByMap(map);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }
//    /**
//     * top10统计
//     * @param begin
//     * @param end
//     * @return
//     */
//    public SalesTop10ReportVO getStatisticsWithTop10(String begin, String end) {
//        List<OrderDetail> list = orderDetailMapper.findByTime(begin,end);
//        String name = "";
//        String number = "";
//        for(OrderDetail orderDetail : list){
//            if(orderDetail.equals(list.get(list.size() - 1))){
//                name = name + orderDetail.getName();
//                number = number + orderDetail.getNumber();
//            }else {
//                name = name + orderDetail.getName() + ",";
//                number = number + orderDetail.getNumber() + ",";
//            }
//        }
//
//        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
//                .nameList(name)
//                .numberList(number)
//                .build();
//        return salesTop10ReportVO;
//    }



//    /**
//     * 用户统计
//     * @param begin
//     * @param end
//     * @return
//     */
//    public UserReportVO userStatistics(String begin, String end) {
//        List<UserReportVO> list = reportMapper.getUserStatistics(begin,end);
//        String newUser = "";
//        String totalUser = "";
//        String date = "";
//        for(UserReportVO userReportVO : list){
//            if(userReportVO.equals(list.get(list.size() - 1))){
//                String time =userReportVO.getDateList();
//                date = date + time;
//                newUser = newUser + userReportVO.getNewUserList();
//                totalUser = totalUser + userReportVO.getTotalUserList();
//
//            }else {
//                String time =userReportVO.getDateList();
//                date = date + time + ",";
//                newUser = newUser + userReportVO.getNewUserList() + ",";
//                totalUser = totalUser + userReportVO.getTotalUserList() + ",";
//            }
//        }
//        UserReportVO userReport = UserReportVO.builder()
//                .totalUserList(totalUser)
//                .newUserList(newUser)
//                .dateList(date)
//                .build();
//        return userReport;

//        //优化修改版本
//        List<UserReportVO> list = reportMapper.getUserStatisticsPlus(begin,end);
//        List<UserReportVO> list1 = reportMapper.getUserStatisticsPlus(null,end);
//        String newUser = "";
//        String totalUser = "";
//        String date = "";
//        for(UserReportVO userReportVO : list){
//            if(userReportVO.equals(list.get(list.size() - 1))){
//                String time =userReportVO.getDateList();
//                date = date + time;
//                newUser = newUser + userReportVO.getNewUserList();
//            }else {
//                String time =userReportVO.getDateList();
//                date = date + time + ",";
//                newUser = newUser + userReportVO.getNewUserList() + ",";
//            }
//        }
//        for(UserReportVO userReportVO1 : list1){
//            if(userReportVO1.equals(list.get(list.size() - 1))){
//                totalUser = totalUser + userReportVO1.getTotalUserList();
//
//            }else {
//                totalUser = totalUser + userReportVO1.getTotalUserList() + ",";
//            }
//        }
//        UserReportVO userReport = UserReportVO.builder()
//                .totalUserList(totalUser)
//                .newUserList(newUser)
//                .dateList(date)
//                .build();
//        return userReport;
//    }



//    /**
//     * 有效订单统计
//     * @param begin
//     * @param end
//     * @return
//     */
//    public OrderReportVO ordersStatistics(String begin, String end) {
//        List<OrderReportVO> list = reportMapper.getOrdersStatistics(begin,end);
//        String orderCount = "";
//        String validOrderCount = "";
//        String date = "";
//        Integer orderNumber = 0;
//        Integer validOrderNumber = 0;
//        for(OrderReportVO orderReportVO : list){
//            if(orderReportVO.equals(list.get(list.size() - 1))){
//                String time =orderReportVO.getDateList();
//                //日期集合
//                date = date + time;
//                //总订单集合
//                orderCount = orderCount + orderReportVO.getOrderCountList();
//                //有效订单集合
//                validOrderCount = validOrderCount + orderReportVO.getValidOrderCountList();
//                //总订单数量
//                orderNumber = orderNumber + Integer.parseInt(orderReportVO.getOrderCountList());
//                //有效订单数量
//                validOrderNumber = validOrderNumber + Integer.parseInt(orderReportVO.getValidOrderCountList());
//
//
//            }else {
//                String time =orderReportVO.getDateList();
//                //日期集合
//                date = date + time + ",";
//                //总订单集合
//                orderCount = orderCount + orderReportVO.getOrderCountList() + ",";
//                //有效订单集合
//                validOrderCount = validOrderCount + orderReportVO.getValidOrderCountList() + ",";
//                //总订单数量
//                orderNumber = orderNumber + Integer.parseInt(orderReportVO.getOrderCountList());
//                //有效订单数量
//                validOrderNumber = validOrderNumber + Integer.parseInt(orderReportVO.getValidOrderCountList());
//
//
//            }
//        }
//        //订单完成率
//        Double orderCompletionRate =  ((double)validOrderNumber/orderNumber);
//        OrderReportVO vo = OrderReportVO.builder()
//                .dateList(date)
//                .orderCompletionRate(orderCompletionRate)
//                .totalOrderCount(orderNumber)
//                .orderCountList(orderCount)
//                .validOrderCountList(validOrderCount)
//                .validOrderCount(validOrderNumber)
//                .build();
//        return vo;
//    }
    /**
     * 视频top10统计
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getStatisticsWithTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        List<GoodsSalesDTO> list = orderDetailMapper.findByTime(beginTime,endTime);
        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());



        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
        return salesTop10ReportVO;
    }

    /**
     * 视频有效订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate  begin, LocalDate end) {
        //封装日期集合
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //封装营业额
        List<Integer>  orderCountList = new ArrayList<>();
        List<Integer>  validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer totalValidOrderCount = 0;
        for(LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer orderCount = ordersMapper.getOrdersStatistics(map);
            orderCountList.add(orderCount);
            totalOrderCount = totalOrderCount + orderCount;
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = ordersMapper.getOrdersStatistics(map);
            validOrderCountList.add(validOrderCount);
            totalValidOrderCount = totalValidOrderCount + validOrderCount;
        }

        Double orderCompletionRate = (double)totalValidOrderCount/totalOrderCount;
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .validOrderCount(totalValidOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workSpaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
